package com.globallogic.model.service;

import java.util.ArrayList;
import java.util.List;

import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;

import com.globallogic.model.dao.UserDao;
import com.globallogic.model.entity.User;
import com.globallogic.model.transferobject.UserTo;

@Stateless
public class UserService {

	@TransactionAttribute(TransactionAttributeType.REQUIRED)
	public List<UserTo> getUsers() {
		List<UserTo> userList = new ArrayList<UserTo>();

		for (User user : userDao.getAll()) {
			userList.add(user.getTo());
		}

		return userList;
	}

	@TransactionAttribute(TransactionAttributeType.REQUIRED)
	public boolean deleteUser(String username) {
		return userDao.delete(username);
	}

	@TransactionAttribute(TransactionAttributeType.REQUIRED)
	public int registerUser(User user) {

		User checkUser = userDao.getByName(user.getName());
		User createdUser;

		if (null == checkUser) {
			createdUser = userDao.insert(user);
			return createdUser.getId();
		} else {
			return -1;
		}

	}

	@TransactionAttribute(TransactionAttributeType.REQUIRED)
	public int updateUser(UserTo userTo) {
		User userToUpdate = userDao.getByName(userTo.getName());
		
		if (null != userToUpdate) {
			userTo.setId(userToUpdate.getId());
			
			User updatedUser = userDao.update(userTo.getEntity());
			System.out.println("UserService.updatedUser: " + updatedUser);
			return updatedUser.getId();
		} else {
			return -1;
		}

	}

	@TransactionAttribute(TransactionAttributeType.REQUIRED)
	public LoginResult login(String name, String password) {
		User checkUser = userDao.getByName(name);

		if (null == checkUser) {
			return LoginResult.ERROR;
		}

		if (!checkUser.getPassword().equals(password)) {
			return LoginResult.ERROR;
		}

		if (checkUser.getIsAdmin()) {
			return LoginResult.ADMIN;
		} else {
			return LoginResult.USER;
		}

	}

	@TransactionAttribute(TransactionAttributeType.REQUIRED)
	public UserTo getUser(String name) {
		User entity = userDao.getByName(name);

		if (null == entity) {
			return null;
		} else {
			return entity.getTo();
		}

	}

	@TransactionAttribute(TransactionAttributeType.REQUIRED)
	public UserTo findUser(String name) {
		User entity = userDao.getByName(name);

		if (null == entity) {
			return null;
		} else {
			return entity.getTo();
		}

	}

	@EJB
	private UserDao userDao;

}
